<template>
  <div class="compute-progress">
    <div class="compute-status">
      <div class="status-indicator" :class="{ active: store.loading }">
        <CircularProgress 
          v-if="store.loading" 
          :progress="store.pageStates.progress"
          :size="44"
          :stroke-width="6"
          :show-text="true"
        />
        <!-- <div v-else class="status-dot"></div> -->
      </div>
    </div>
    <!-- <button 
      class="compute-toggle-btn" 
      :class="{ active: isEnabled }"
      @click="toggleCompute"
    >
      {{ isEnabled ? '关闭' : '开启' }}
    </button> -->
    <button 
      v-if="!store.loading"
      class="compute-toggle-btn" 
      @click="toggleCompute"
    >
      {{ store.runningData ? '关闭云电脑' : '开启云电脑' }}
    </button>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import CircularProgress from './CircularProgress.vue'
import { dialog } from '@/utils/dialog'
import { useStore } from '@/stores/data'

const store = useStore();

// 定义 props
const props = defineProps({
  // 初始状态
  initialEnabled: {
    type: Boolean,
    default: false
  }
})

// 定义 emits
const emit = defineEmits(['toggle'])

// 状态
const isEnabled = ref(props.initialEnabled)

// 进度条状态 - 使用 store 全局状态
let progressInterval = null
const totalDuration = 120000 // 两分钟，单位毫秒
const startTime = ref(0)

// 基于时间模拟进度，但最终进度取决于 store.runningData
const calculateProgress = () => {
  if (!startTime.value) return 0
  
  const elapsed = Date.now() - startTime.value
  const timeBasedProgress = Math.min((elapsed / totalDuration) * 100, 100)
  
  // 只有当 store.runningData 不为 null 时，进度才能达到 100%
  if (store.runningData !== null) {
    return Math.min(timeBasedProgress, 100)
  } else {
    // 如果没有 runningData，进度最多只能到 99%
    return Math.min(timeBasedProgress, 99)
  }
}

// 启动进度模拟
const startComputeProgress = () => {
  // 如果已经有进度在运行，先停止
  if (progressInterval) {
    stopComputeProgress()
  }
  
  // 重置进度为0开始新的进度模拟
  store.pageStates.progress = 0
  startTime.value = Date.now()
  
  progressInterval = setInterval(() => {
    store.pageStates.progress = calculateProgress()
    
    // 如果达到100%且 store.runningData 不为 null，停止计时器
    if (store.pageStates.progress >= 100 && store.runningData !== null) {
      stopComputeProgress()
    }
    
    // 如果超过两分钟但 store.runningData 仍为 null，也停止计时器
    if (Date.now() - startTime.value >= totalDuration && store.runningData === null) {
      stopComputeProgress()
      store.pageStates.progress = 99 // 停留在99%
    }
  }, 100) // 每100毫秒更新一次
}

// 停止进度模拟
const stopComputeProgress = () => {
  if (progressInterval) {
    clearInterval(progressInterval)
    progressInterval = null
  }
}

// 切换运算力
const toggleCompute = () => {
  // isEnabled.value = !isEnabled.value
  // emit('toggle', isEnabled.value)
  
  // if (isEnabled.value) {
  //   // 开启运算力时启动进度模拟
  //   startComputeProgress()
  //   dialog.alert({ iconType: 'sc', message: '云算力已开启' })
  // } else {
  //   // 关闭时重置进度
  //   stopComputeProgress()
  //   store.pageStates.progress = 0
  //   dialog.alert({ iconType: 'sc', message: '云算力已关闭' })
  // }
  store.showOpen({})
}

// 监听 store.runningData 变化，自动更新进度
watch(() => store.runningData, (newData) => {
  if (newData && isEnabled.value) {
    // runningData 变为 true 时，重新计算进度
    console.log('Running data updated, progress recalculated')
  }
}, { deep: true })

// 监听 isEnabled 变化
watch(isEnabled, (newValue) => {
  if (!newValue) {
    // 关闭云算力时停止进度模拟
    stopComputeProgress()
    store.pageStates.progress = 0
  }
})

// 组件挂载时初始化
onMounted(() => {
  // 只有当没有运行中的进度且进度小于100%时，才启动新的进度模拟
  if (!progressInterval && store.pageStates.progress < 100) {
    // 如果已经有进度值，基于当前进度继续计算
    if (store.pageStates.progress > 0) {
      // 计算剩余时间并设置开始时间
      const elapsedPercentage = store.pageStates.progress / 100
      const elapsedTime = elapsedPercentage * totalDuration
      startTime.value = Date.now() - elapsedTime
    } else {
      startTime.value = Date.now()
    }
    
    // 启动进度模拟
    progressInterval = setInterval(() => {
      store.pageStates.progress = calculateProgress()
      
      // 如果达到100%且 store.runningData 不为 null，停止计时器
      if (store.pageStates.progress >= 100 && store.runningData !== null) {
        stopComputeProgress()
      }
      
      // 如果超过两分钟但 store.runningData 仍为 null，也停止计时器
      if (Date.now() - startTime.value >= totalDuration && store.runningData === null) {
        stopComputeProgress()
        store.pageStates.progress = 99 // 停留在99%
      }
    }, 100)
  }
})

// 组件卸载时清理
onUnmounted(() => {
  stopComputeProgress()
})
</script>

<style scoped>
.compute-progress {
  display: flex;
  align-items: center;
  gap: 12px;
}

.compute-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-indicator {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.status-dot {
  width: 8px;
  height: 8px;
  background: #666;
  border-radius: 50%;
}

.compute-toggle-btn {
  padding: 6px 12px;
  border-radius: 16px;
  border: 1px solid #ffffff;
  background: transparent;
  color: #ffffff;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.compute-toggle-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.compute-toggle-btn.active {
  background: #006CFF;
  border-color: #006CFF;
  color: #ffffff;
}

.compute-toggle-btn.active:hover {
  background: #005ce6;
}
</style>